package com.cppe.http;


import androidx.annotation.IntDef;

import com.google.gson.Gson;

import java.io.IOException;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkClient {

    private OkHttpClient mOkHttpClient;

    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    public static final int POST = 0;
    public static final int GET = 1;

    @IntDef({POST, GET})
    @Retention(RetentionPolicy.SOURCE)
    public @interface Method {
    }


    private OkClient() {
        mOkHttpClient = new OkHttpClient.Builder()
                .connectTimeout(15, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .build();
    }

    public static OkClient getInstance() {
        return OkClientSingleton.INSTANCE;
    }


    private static class OkClientSingleton {
        static final OkClient INSTANCE = new OkClient();
    }


    public void doPost(String url, Map<String, Object> params, Callback callback) {
        RequestBody body = RequestBody.create(JSON, new Gson().toJson(params));
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(callback);
    }


}


